<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>自定义表</title>
        <#include "/pubHeadStyle.html">
        <link rel="stylesheet" href="${ctx}/css/form.css">
        <script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
        <script src="${ctx}/formStatic/verify.js"></script>
    </head>
    <body>
        <form class="layui-form" action="" lay-filter="formData"
              style="height: 100%;background: #fff;padding-top:10px;">
            <div style="position: absolute;bottom:12px;left:43%">
                <button class="layui-btn" lay-submit="" lay-filter="save">保存
                </button>
                <button class="layui-btn layui-btn-danger" id="return">取消</button>
            </div>
            <button style="position: absolute;top: 14px;left:17px;z-index: 100;"
                    class="layui-btn layui-btn layui-btn-sm" lay-tips="添加列" type="button" id="addCol"><i
                    class="layui-icon layui-icon-add-1"></i></button>
            <div class="addSearch">
                <div class="layui-form-item" style="padding-left: 77px;">
                    <label class="layui-form-label">注释<span style="color:red;">*</span></label>
                    <div class="layui-input-inline">
                        <input type="text" name="tableDesc" id="tableDesc" lay-verify="required" autocomplete="off"
                               placeholder="" onblur="autoGetTableName(this)"
                               class="layui-input" maxlength="25">
                    </div>
                    <label class="layui-form-label">表名<span style="color:red;">*</span></label>
                    <div class="layui-input-inline">
                        <input type="text" name="tableName" id="tableName" lay-verify="required|customTableName|startLetter" placeholder=""
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否主表</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="isMain" value="1" title="主表" lay-filter="switch" checked="">
                        <input type="radio" name="isMain" value="0" title="从表" lay-filter="switch">
                    </div>
                    <label class="layui-form-label">所属主表</label>
                    <a id="showMainTable" href=""
                       style="display: none;line-height: 36px;margin-left:10px;color:blue;cursor: pointer"></a>
                    <div class="layui-input-inline" id="fieldattr" style="position: relative;display: none;">
                        <input type="radio" name="publishedasmain" value="未生成的表" title="未生成的表" lay-filter="state"
                               checked="">
                        <input type="radio" name="publishedasmain" value="已生成的表" title="已生成的表" lay-filter="state">
                        <select name="initTable" id="initTable" lay-filter="initTable">
                            <option value=""></option>
                        </select>
                        <input type="hidden" value="" name="mainTableId" id="mainTableId">
                        <div id="choice" style="display:none">
                            <button type="button" class="layui-btn layui-btn-sm" style="float: left;margin-top:-3px;"
                                    id="choiceTable"><i class="layui-icon layui-icon-search"></i></button>
                            <input type="text" name="mainTableName" id="mainTableName" autocomplete="off"
                                   class="layui-input"
                                   style="float: left;width: 100px;margin-top:-7px;margin-left:5px;">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否公开</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="isPublic" value="0" title="不公开">
                        <input type="radio" name="isPublic" value="1" title="公开" checked="">
                    </div>
                    <label class="layui-form-label">控制表单版本</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="needVer" value="0" title="否" checked="">
                        <input type="radio" name="needVer" value="1" title="是">
                    </div>
                </div>
            </div>
            <div class="tableHeight">
                <table class="layui-hide" id="custom" lay-filter="custom"></table>
            </div>
        </form>


        <script type="text/html" id="operation">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs" lay-event="moveUp">上移</a>
            <a class="layui-btn layui-btn-xs" lay-event="moveDown">下移</a>
            {{# if('${isExternal}' == 0){ }}
            <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
            {{# }}}
        </script>
        <script>
            var isExternal = '${isExternal}';
            var tableId = '${tableId}';
            var categoryId = '${categoryId}';
            var setter;

            layui.config({
                base: serverPath.formPath + staticPath.formPath //静态资源所在路径
            }).extend({
                index: 'index' //主入口模块
            }).use(['index', 'setter', 'commons', 'form', 'jquery', 'layer','table'], function () {
                var form = layui.form, layer = layui.layer;
                setter = layui.setter, totalFilter = layui.totalFilter,commons=layui.commons;
                var table = layui.table;
                var $ = layui.$;
                $('#addCol').on('click', function () {
                    layer.open({
                        type: 2,
                        title: "添加列",
                        shade: 0.3,
                        area: ['800px', '490px'],
                        content: serverPath.formPath +  setter.formLinkPath + 'table/view/addCol?isAdd=1'
                    })
                });
                //请求数据回显
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + "table/list",
                    type: "GET",
                    contentType: 'application/json',
                    dataType: 'json',
                    data: {"isMain": "1", "isPublished": "0"},
                    success: function (data) {
                        var returnDate = data.data;
                        $.each(returnDate, function (index, objVal) {
                            //未生成的表编辑时候,选择从表时候排除自己
                            if (objVal.tableId != tableId) {
                                $("#initTable").append("<option value=" + objVal.tableId + ">" + objVal.tableDesc + "</option>");
                            }
                        });
                        form.render();
                    }
                });
                var retArray = [];
                layui.getFieldValue = function (retFields, isAdd, index) {
                    if (isAdd == 0) {
                        retArray[index] = retFields;
                    } else {
                        retArray.push(retFields);
                    }
                    table.render({
                        elem: '#custom'
                        , data: retArray
                        , cellMinWidth: 80
                        , height: 'full-300'
                        , cols: [[
                            {field: 'fieldName', title: '列名', align: 'center'}
                            , {field: 'fieldDesc', title: '注释', align: 'center'}
                            , {
                                field: 'fieldType', title: '类型', align: 'center',
                                templet: function (d) {
                                    if (d.fieldType == "varchar") {
                                        return d.fieldType + "(" + d.charLen + ")";
                                    } else if (d.fieldType == "number") {
                                        return d.fieldType + "(" + d.intLen + "," + d.decimalLen + ")";
                                    } else {
                                        return d.fieldType;
                                    }
                                }
                            }
                            , {
                                field: 'isRequired', title: '必填', align: 'center',
                                templet: function (d) {
                                    if (d.isRequired == 1) {
                                        return '<input type="checkbox" lay-skin="primary" name="isRequired" checked/>';

                                    }
                                    return '<input type="checkbox" lay-skin="primary" name="isRequired"/>';
                                }
                            }
                            , {
                                field: 'isList', title: '显示到列表', align: 'center',
                                templet: function (d) {
                                    if (d.isList == 1) {
                                        return '<input type="checkbox" lay-skin="primary" name="isList" checked/>';

                                    }
                                    return '<input type="checkbox" lay-skin="primary" name="isList"/>';
                                }
                            }
                            , {
                                field: 'isFlowVar', title: '是否流程变量', align: 'center',
                                templet: function (d) {
                                    if (d.isFlowVar == 1) {
                                        return '<input type="checkbox" lay-skin="primary" name="isFlowVar" checked/>';

                                    }
                                    return '<input type="checkbox" lay-skin="primary" name="isFlowVar"/>';
                                }
                            }
                            , {field: 'operation', toolbar: '#operation', title: '管理', align: 'center'}
                        ]]
                        , page: false
                        , limit: 1000
                        , done: function (data) {
                            allFields = data.data;
                        }
                    });
                };
                layui.getEditData = function () {
                    return editData;
                };
                var allFields;
                layui.getAllFields = function () {
                    return allFields;
                };
                //选择表弹窗
                $('#choiceTable').on('click', function () {
                    layer.open({
                        type: 2,
                        title: "选择表",
                        shade: 0.3,
                        area: ['800px', '500px'],
                        content: serverPath.formPath +  setter.formLinkPath + "table/view/generTable"
                    })
                });
                if (tableId) {
                    $.ajax({
                        url: serverPath.formPath + setter.formLinkPath + "table/getByTableId?tableId=" + tableId,
                        dataType: 'json',
                        success: function (data) {

                            //表单初始赋值
                            var returnData = data.data;
                            var fieldList = returnData.fields;
                            var tableInfo = returnData.table;
                            if (tableInfo.isPublished == 1) { //如果已经生成物理表 不能修改是否主表和表名
                                $("input[name='isMain']").attr("disabled", "disabled");
                                $("input[name='tableName']").attr("disabled", "disabled");
                                $("#tableName").css("background", "#ebebeb");
                            }

                            if (tableInfo.isMain == 0) {
                                $("#showMainTable").show();
                                $("#showMainTable").text(tableInfo.mainTableDesc);
                                $('#mainTableId').val(tableInfo.mainTableId);
                                $("#showMainTable").attr("href", serverPath.formPath +  setter.formLinkPath + 'table/view/detailed?tableId=' + tableInfo.mainTableId);
                            }
                            if (tableInfo.isExternal == 1) {
                                $("#hiddenDelete").hide();
                            }
                            form.val('formData', {
                                "tableName": tableInfo.tableName,
                                "tableDesc": tableInfo.tableDesc,
                                "isMain": tableInfo.isMain + "",
                                "isPublic": tableInfo.isPublic + "",
                                "needVer": tableInfo.needVer + ""
                            });
                            //将编辑的列数据放到数组中
                            retArray = fieldList;
                            //表格渲染数据
                            table.render({
                                elem: '#custom'
                                , cellMinWidth: 80
                                , data: fieldList
                                , height: 'full-300'
                                , cols: [[
                                    {field: 'fieldName', title: '列名', align: 'center'}
                                    , {field: 'fieldDesc', title: '注释', align: 'center'}
                                    , {
                                        field: 'fieldType', title: '类型', align: 'center',
                                        templet: function (d) {
                                            if (d.fieldType == "varchar") {
                                                return d.fieldType + "(" + d.charLen + ")";
                                            } else if (d.fieldType == "number") {
                                                return d.fieldType + "(" + d.intLen + "," + d.decimalLen + ")";
                                            } else {
                                                return d.fieldType;
                                            }
                                        }
                                    }
                                    , {
                                        field: 'isRequired', title: '必填', align: 'center',
                                        templet: function (d) {
                                            if (d.isRequired == 1) {
                                                return '<input type="checkbox" lay-skin="primary" name="isRequired" checked/>';

                                            }
                                            return '<input type="checkbox" lay-skin="primary" name="isRequired"/>';
                                        }
                                    }
                                    , {
                                        field: 'isList', title: '显示到列表', align: 'center',
                                        templet: function (d) {
                                            if (d.isList == 1) {
                                                return '<input type="checkbox" lay-skin="primary" name="isList" checked/>';

                                            }
                                            return '<input type="checkbox" lay-skin="primary" name="isList"/>';
                                        }
                                    }
                                    , {
                                        field: 'isFlowVar', title: '是否流程变量', align: 'center',
                                        templet: function (d) {
                                            if (d.isFlowVar == 1) {
                                                return '<input type="checkbox" lay-skin="primary" name="isFlowVar" checked/>';

                                            }
                                            return '<input type="checkbox" lay-skin="primary" name="isFlowVar"/>';
                                        }
                                    }
                                    , {
                                        field: 'operation',
                                        toolbar: '#operation',
                                        title: '管理',
                                        align: 'center'
                                    }
                                ]]
                                , page: false
                                , limit: 1000
                                , done: function (data) {
                                    allFields = data.data;
                                }
                            })
                        }
                    });
                } else {
                    //只加载一个表头
                    table.render({
                        elem: '#custom'
                        , cellMinWidth: 80
                        , data: []
                        , cols: [[
                            {field: 'fieldName', title: '列名', align: 'center'}
                            , {field: 'fieldDesc', title: '注释', align: 'center'}
                            , {field: 'fieldType', title: '类型', align: 'center'}
                            , {field: 'isRequired', title: '必填', align: 'center'}
                            , {field: 'isList', title: '显示到列表', align: 'center'}
                            , {field: 'isFlowVar', title: '是否流程变量', align: 'center'}
                            , {field: 'operation', toolbar: '#operation', title: '管理', align: 'center'}
                        ]]
                    })
                }
                //弹窗关闭方法
                var index = parent.layer.getFrameIndex(window.name);
                $('#return').click(function () {
                    parent.layer.close(index);
                });

                var editData = "";
                table.on('tool(custom)', function (obj) {
                    editData = obj.data;
                    var editFieldName = obj.data.fieldName;
                    switch (obj.event) {
                        case 'edit':
                            var editIndex = $(this).parent().parent().parent().attr("data-index");
                            layer.open({
                                type: 2,
                                title: "编辑列",
                                shade: 0.3,
                                content: serverPath.formPath +  setter.formLinkPath + "table/view/addCol?isAdd=0&editIndex=" + editIndex + "&tableId=" + tableId + "&editFieldName=" + editFieldName + '&isExternal=' + isExternal,
                                area: ['800px', '490px']
                            });
                            break;
                        case 'moveUp':
                            var upTr = $(this).parent().parent().parent();
                            $(upTr).insertBefore($(upTr).prev());
                            break;
                        case 'moveDown':
                            var downTr = $(this).parent().parent().parent();
                            $(downTr).insertAfter($(downTr).next());
                            break;
                        case 'del':
                            var oldData = table.cache.custom;
                            oldData.splice(obj.tr.data('index'), 1);
                            table.reload('custom', {data: oldData});
                            retArray.splice(obj.tr.data('index'), 1);
                            obj.tr.remove();
                            break;
                    }
                });

                //监听select(initTable)
                form.on('select(initTable)', function (data) {
                    // $('#mainTableName').val(data.elem[data.elem.selectedIndex].text);
                    $('#mainTableId').val(data.value);
                    form.render('select');
                    return false;
                });

                //复选框设置
                function tableCheckboxData(oldData) {
                    $('.tableHeight [name="isRequired"]').each(function (i, item) {
                        oldData[i].isRequired = $(this)[0].checked ? 1 : 0;
                    });
                    $('.tableHeight [name="isList"]').each(function (i, item) {
                        oldData[i].isList = $(this)[0].checked ? 1 : 0;
                    });
                    $('.tableHeight [name="isFlowVar"]').each(function (i, item) {
                        oldData[i].isFlowVar = $(this)[0].checked ? 1 : 0;
                    });
                    return oldData;
                }

                //监听提交
                form.on('submit(save)', function (data) {
                    var tableData = tableCheckboxData(table.cache.custom);
                    table.render();
                    data['field']['tableId'] = tableId;

                    if (data['field']['isMain'] == 0 && $('#mainTableId').val() == "") {
                        layer.alert("请选择主表！");
                        return false;
                    }
                    if (table.cache.custom == undefined) {
                        layer.alert("没有添加字段信息!");
                        return false;
                    }
                    $.ajax({
                        url: serverPath.formPath + setter.formLinkPath + 'table/add',
                        type: "post",
                        dataType: 'json',
                        data: {
                            "table": JSON.stringify(data['field']),
                            "fields": JSON.stringify(tableData),
                            "categoryId": categoryId
                        },
                        success: function (data) {
                            if (data.code == 0) {
                                layer.alert(data.msg, {skin: 'btn-class'}, function () {
                                    commons.bulletWindow(index);
                                    parent.layui.table.reload('customTable', {
                                        page: {
                                            curr: 1
                                        }
                                    });
                                    parent.layui.totalFilter.init('customTable');
                                });
                            } else {
                                layer.alert(data.msg, {skin: 'btn-class'});
                            }
                        }
                    });
                    return false;
                });
                //监听主表从表radio选项
                form.on('radio(switch)', function (data) {
                    if (data.value == '0') {
                        $('#fieldattr').css("display", "block");
                    } else {
                        $('#fieldattr').css("display", "none");
                        $("#showMainTable").text("");
                        $('#mainTableId').val("");
                    }
                    form.render();
                });
                form.on('radio(state)', function (data) {
                    if (data.value == '未生成的表') {
                        $('#fieldattr .layui-form-select').css("display", "block");
                        $('#choice').css("display", "none");
                    } else if (data.value == "已生成的表") {
                        $('#fieldattr .layui-form-select').css("display", "none");
                        $('#choice').css("display", "block");
                    }
                });
            });

            /**
             * 根据字段描述生成字段名
             * @param inputObj
             */
            function autoGetTableName(inputObj) {
                var tableDesc = $(inputObj).val();
                if ($.trim(tableDesc).length < 1) return;
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + "table/getFieldKey",
                    dataType: 'json',
                    data: ({fieldDesc: tableDesc}),
                    success: function (obj) {
                        if (commons._filterRecord(obj)) {
                            if (tableId == '' || tableId == null) {
                                $("#tableName").val(obj.data);
                            }
                        }
                    }
                });
            }
        </script>
        <style>
            .layui-table-body {
                overflow-x: hidden;
            }

            #fieldattr .layui-form-select {
                width: 180px;
                position: absolute;
                left: 235px;
                top: 0;
            }

            #fieldattr #choice {
                position: absolute;
                top: 17%;
                left: 235px;
                width: 80%;
            }
        </style>
    </body>
</html>